from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
import jwt
from ronglian_sms_sdk import SmsSDK
from meiduo_admin_pro.settings import SID, Token, APPID
from .utils import make_code
import json
from django.core.cache import cache
from .sers import *
from rest_framework.viewsets import ModelViewSet


# 使用Django自带的缓存来实现 数据的 有效期缓存


class LoginView(APIView):
    def post(self, request):
        username = request.data.get("username")
        password = request.data.get("password")

        user = User.objects.filter(username=username, password=password).first()
        if user:
            if not user.phone:
                return Response({"msg": "用户还没有绑定手机号,请先绑定在登录", "code": 300, "uid": user.id})
            else:
                token = jwt.encode({"uid": user.id}, "1234")
                return Response({"msg": "登录成功", "code": 200, "token": token})
        else:
            return Response({"msg": "登录失败", "code": 400})


class SendCodeView(APIView):
    def get(self, request):
        sdk = SmsSDK(SID, Token, APPID)
        """
        【云通讯】您的验证码是{1}，请于{2}分钟内正确输入
        """
        phone = request.GET.get("phone")
        # 导入utils工具类中的 函数 生成随机验证码
        code = make_code(4)
        # 存入到缓存中 根据手机号存入
        cache.set(phone, code)

        r = sdk.sendMessage(1, phone, (code, "3"))
        # 使用json模块 把字符串 转成字典
        resp = json.loads(r)
        print("r:================start")
        print(r)
        print("r:=================end")
        print(resp)

        if resp["statusCode"] == "000000":
            # 发送成功
            return Response({"msg": "发送成功", "code": 200})
        else:
            return Response({"msg": "发送失败", "code": 400})


class UserView(APIView):
    def put(self, request):
        # 绑定手机号操作
        phone = request.data.get("phone")
        # 获取 验证码
        code = request.data.get("code")

        code1 = cache.get(phone)
        # 验证 验证码 把传递来的code 和 服务端保存的code进行比较
        if code1:
            if code == code1:
                # 表示 验证码对的
                # 绑定手机号
                uid = request.data.get("uid")
                User.objects.filter(id=uid).update(phone=phone)
                return Response({"msg": "绑定手机号成功", "code": 200})
            else:
                return Response({"msg": "验证码不一致", "code": 400})
        else:
            return Response({"msg": "验证码失效，请重新获取", "code": 400})


# 进行菜单权限列表
class ControlMenuView(APIView):

    def get(self, request):
        #  我们要根据用户 的令牌 去获取 该用户下 有哦哪些 菜单能够展示
        token = request.GET.get("token")
        uid = jwt.decode(token, '1234')["uid"]

        # 根据用户去查找 角色对象id
        role_id = User.objects.get(id=uid).role_id

        # 根据角色 去查找 该角色下所有菜单权限
        #  先查询一级菜单
        queryset = RoleControlMenu.objects.filter(role_id=role_id, control__parent=None)

        # 获取到了所有的权限，这里有一个问题，就是说
        ser = RoleControlMenuListSer(queryset, many=True)
        return Response(ser.data)


# 对角色进行增删改查
class RoleViewSet(ModelViewSet):
    queryset = Role.objects.all()
    serializer_class = RoleSer

